<?php

// +----------------------------------------------------------------------

namespace app\user\home;

use app\common\controller\BaseController;
use app\user\model\User as UserModel;
use app\user\model\Role as RoleModel;
use util\Wxsdk;
use think\Db;

/**
 * 用户首页控制器
 * @package app\index\controller
 */
class Wechat extends BaseController
{
	public function auto()
	{
		$uid = is_signin();
		if($uid == 0){
			if (!cookie('?__wxback__')) cookie('__wxback__',url('user/index/index'));
			$out = urlencode(config('wechat.out'));
			if($out){
				$url = $out;
				$re_url = url('user/wechat/wxsign','', '', true);
				$re_url = urlencode($re_url);
				$api = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat.appid').'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state='.$re_url.'#wechat_redirect';
			}else{
				$data['url'] = url('user/wechat/wxsign','', '', true);
				$url = urlencode($data['url']);
				$api = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat.appid').'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=ok#wechat_redirect';
			}
			return redirect($api);
		}else{
			return redirect(url('user/index/index'));
		}
	}
	//微信登录
	public function wxsign()
	{
		// 获取数据
		$data = $this->request->param();

		if(isset($data['state']) && isset($data['code'])){
			//换取TOKEN
			$api = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wechat.appid').'&secret='.config('wechat.appsecret').'&code='.$data['code'].'&grant_type=authorization_code';
			$get_token = json_decode(post_curls($api, []), true);
			if(isset($get_token['access_token'])){
				$UserModel = new UserModel;
				$user = $UserModel::where('openid', $get_token['openid'])->where('status', 1)->find();
				session('user_token', $get_token);
				if($user){
					cache('wx'.$data['state'], $get_token['openid'], 300);
					$data = [
						'code'		=> 1,
						'title'		=> '登录成功',
						'summary'	=> '微信授权登录成功，点击确定关闭该页面！',
					];
				}else{
					session('code', $data['state']);
					$data = [
						'code'		=> 0,
						'title'		=> '登录失败',
						'summary'	=> '微信授权登录失败，如有需要请联系管理员，点击确定关闭该页面！',
					];
					return redirect(url('user/wechat/bind'));
				}
				//微信SDK支持
				$wxsdk = new Wxsdk;
				$jssdk = $wxsdk->getWxSdk();
				if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
				$this->assign('data', $data);
				return $this->fetch();
			}else{
				$this->error('登录失败('.$get_token['errcode'].')');
			}
		}else{
			$this->error('请先关注公众号');
		}
	}
	/**
	 * 用户绑定
	 * @param string $username 用户名
	 * @param string $password 密码
	 * @author paulxun
	 * @return bool|mixed
	 */
	public function bind()
	{
		if (request()->isPost()) {
			// 获取数据
			$data = request()->post();
			$username = trim($data['username']);
			$password = trim($data['password']);
			$map = [
				['status', '=', 1],
				['openid', '=', ''],
			];
			// 匹配方式
			if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $username)) {
			    // 邮箱登录
				$map[] = ['email', '=', $username];
			} elseif (preg_match("/^1\d{10}$/", $username)) {
			    // 手机号登录
			    $map[] = ['mobile', '=', $username];
			} else {
			    // 用户名登录
			    $map[] = ['username', '=', $username];
			}
				
			// 查找用户
			$user = UserModel::where($map)->find();
			if (!$user) {
			    $this->error('用户不存在，或已绑定微信用户');
			} else {
			    // 检查是否分配用户组
			    if ($user['role'] == 0) {
			        $this->error('禁止访问，原因：未分配角色！');
			    }
			    // 检查是可登录后台
			    if (!RoleModel::where(['id' => $user['role'], 'status' => 1])->value('access')) {
			        $this->error('禁止访问，用户所在角色未启用或禁止访问后台！');
			    }
			    if (MD5((string)$password) != $user['password']) {
			        $this->error( '账号或者密码错误！');
			    } else {
					$get_token = session('user_token');
					$code = session('code');
					if(!$get_token || !$code) $this->error("参数错误");
			        // 更新用户信息
			        $user['last_login_time'] = time();
			        $user['last_login_ip']   = get_client_ip(1);
					$user['openid']   = $get_token['openid'];
			        if ($user->save()) {
			            cache('wx'.$code, $get_token['openid'], 300);
			            $this->success('绑定成功');
			        } else {
			            // 更新登录信息失败
			            $this->error('绑定失败，请重新登录！');
			        }
			    }
			}
		}
	    //微信SDK支持
	    $wxsdk = new Wxsdk;
	    $jssdk = $wxsdk->getWxSdk();
	    if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
		return $this->fetch();
	}
}
